export class UniRouter {
    /**
     * 包装 uni.navigateTo
     * @param url 跳转页面地址
     * @param param 携带参数
     * @param otherParam 其他参数
     * @returns {void} uni.navigateTo运行结果
     */
    static navigateTo(url, param = {}, otherParam = {}) {
        if (url === null || url === undefined) {
            console.log('url无效', url)
            return
        }
        url = url + this.getParamsStr(param)
        // console.log("navigateToMy-->" + url)
        return uni.navigateTo({
            url,
            ...otherParam,
            fail(e) {
                console.log('路由跳转失败', e)
            },
        })
    }

    /**
     * 包装 uni.redirectTo
     * @param url 跳转页面地址
     * @param param 携带参数
     * @param otherParam 其他配合
     * @returns {Promise} uni.redirectTo运行结果
     */
    static redirectTo(url, param = {}, otherParam = {}) {
        if (url === null || url === undefined) {
            console.log('url无效', url)
            return
        }
        url = url + this.getParamsStr(param)
        console.log("redirectToMy-->" + url)
        return uni.redirectTo({
            url,
            ...otherParam
        })
    }

    /**
     * 包装 uni.switchTab
     * @param url 跳转页面地址
     * @returns {Promise} uni.switchTab运行结果
     */
    static switchTab(url) {
        if (url === null || url === undefined) {
            console.log('url无效', url)
            return
        }
        console.log("switchTabMy-->" + url)
        return uni.switchTab({
            url
        })
    }

    /**
     * 包装 uni.reLaunch
     * @param url 跳转页面地址
     * @param param 携带参数
     * @param otherParam 其他参数
     * @returns {void} uni.navigateTo运行结果
     */
    static reLaunch(url,param={},otherParam = {}){
        if (url === null || url === undefined) {
            console.log('url无效', url)
            return
        }
        url = url + this.getParamsStr(param)
        // console.log("navigateToMy-->" + url)
        return uni.reLaunch({
            url,
            ...otherParam,
            fail(e) {
                console.log('路由跳转失败', e)
            },
        })
    }


    /**
     * 包装navigateBack
     * @param params 参数
     */
    static back(params={}){
        uni.navigateBack(params)
    }


    /**
     * 根据参数对象,组装为对应的字符串
     * @param param
     * @returns {string}
     */
    static getParamsStr(param = {}) {
        let str = ""
        //组装查询参数
        for (const [key, value] of Object.entries(param)) {
            if (value === undefined || value === null) {
                continue
            }
            str += `&${key}=${value}`
        }
        //加上 ? 并且去掉无用的字符->&
        if (str.length > 0) {
            str = "?" + str.substring(1)
        }
        return str
    }

}

